package com.sright.bcard.common.biz.manager.impl;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.sright.bcard.common.biz.manager.SmsServiceManager;
import com.sright.bcard.common.service.share.constants.RedisKeyConstants;
import com.sright.bcard.common.service.share.constants.SystemConstants;
import com.sright.bcard.common.service.share.exception.base.BusinessErrorException;
import com.sright.bcard.common.service.share.exception.code.BusinessCode;
import com.sright.bcard.common.service.share.utils.JedisUtil;
import com.sright.bcard.common.service.share.utils.RandomCodeUtils;
import com.sright.bcard.common.service.share.dto.content.NameCodeDTO;
import com.sright.bcard.common.service.share.dto.content.AdminDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class SmsServiceManagerImpl implements SmsServiceManager {

    @Value("${ACCESS_KEY_ID}")
    private String accessKeyId;

    @Value("${ACCESS_KEY_SECRET}")
    private String accessKeySecret;

    @Value("${SIGN_NAME}")
    private String signName;

    @Value("${COMMON_SMS_TMP_CODE}")
    private String commonSmsTmpCode;

    @Value("${PRODUCT}")
    private String product;

    @Value("${DOMAIN}")
    private String domain;

    @Value("${CONNECTTIMEOUT}")
    private String connectTimeOut;

    @Value("${READTIMEOUT}")
    private String readTimeOut;

    @Value("${TIME}")
    private String time;

    @Autowired
    private JedisUtil jedisUtil;

    @Override
    public String smsSend(AdminDTO adminDTO) throws ClientException {
        String code = RandomCodeUtils.codeSix();
        NameCodeDTO nameCodeDTO = new NameCodeDTO();
        nameCodeDTO.setName(SystemConstants.NAME);
        nameCodeDTO.setCode(code);
        String jsonParam = JSON.toJSONString(nameCodeDTO);
        String result = sendMessage(jsonParam,commonSmsTmpCode,adminDTO.getMobile());

        //  验证码保存在redis key是userId value是code
        jedisUtil.setExpire(RedisKeyConstants.ENTERPRISE_CHECK_CODE + adminDTO.getEnterpriseId(), code, 300);
        return result;
    }

    @Override
    public String sendMessage(String jsonParam,String templateCode,String mobile) throws ClientException {
        //设置超时时间-可自行调整
        System.setProperty(connectTimeOut, time);
        System.setProperty(readTimeOut, time);
        //初始化ascClient,暂时不支持多region（请勿修改）
        IClientProfile profile = DefaultProfile.getProfile(SystemConstants.CN_HANGZHOU, accessKeyId,
                accessKeySecret);
        DefaultProfile.addEndpoint(SystemConstants.CN_HANGZHOU, SystemConstants.CN_HANGZHOU, product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //组装请求对象
        SendSmsRequest request = new SendSmsRequest();
        //使用post提交
        request.setMethod(MethodType.POST);
        //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式；发送国际/港澳台消息时，接收号码格式为国际区号+号码，如“85200000000”
        request.setPhoneNumbers(mobile);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(SystemConstants.SRIGHT);
        //必填:短信模板-可在短信控制台中找到，发送国际/港澳台消息时，请使用国际/港澳台短信模版
        request.setTemplateCode(templateCode);
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        request.setTemplateParam(jsonParam);
        //  验证码保存在redis key是userId value是code
        //请求失败这里会抛ClientException异常
        log.info("SmsServiceManager.smsSend send message request params is : {}", JSON.toJSONString(request));
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals(SystemConstants.OK)) {
            //请求成功
            log.info("SmsServiceManager.smsSend success response is : {}", JSON.toJSONString(sendSmsResponse));
            return sendSmsResponse.getMessage();
        } else {
            log.info("SmsServiceManager.smsSend error cause is : {}", JSON.toJSONString(sendSmsResponse));
            throw new BusinessErrorException(BusinessCode.SMS_SEND_MESSAGE);
        }
    }

    @Override
    public String smsSendCommon(AdminDTO adminDTO) {
        // TODO
        return null;
    }
}
